package com.example.netty.server;

import com.example.netty.channel.handler.MyDecoder;
import com.example.netty.channel.handler.MyEncoder;
import com.example.netty.channel.handler.MyHanlder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class NettyTcpMainServer implements NettyServer {
    private final static Logger logger = LoggerFactory.getLogger(NettyTcpMainServer.class);
    private EventLoopGroup boss, woker;

    public NettyTcpMainServer() {
        boss = new NioEventLoopGroup();
        woker = new NioEventLoopGroup();
    }

    @Override
    public void start() {
        try {
            ChannelFuture channelF = new ServerBootstrap().group(boss, woker)
                //此处设置的为NioServerSocketChannel，有server
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                //此处设置的为NioSocketChannel，没有server
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        logger.info(
                            nioSocketChannel.remoteAddress().getHostString() + ":" + nioSocketChannel.remoteAddress()
                                .getPort()+"上线了");
                        nioSocketChannel.pipeline().addLast(new StringDecoder());
                        nioSocketChannel.pipeline().addLast(new MyHanlder());
                        nioSocketChannel.pipeline().addLast(new MyEncoder());
                    }
                })
                .bind(8889).sync();
            logger.info("NettyMainServer started");
            channelF.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //this.stopGracefully();
        }
    }

    @Override
    public void stopGracefully() {
        boss.shutdownGracefully();
        woker.shutdownGracefully();
        logger.info("NettyMainServer stopped");
    }

    @Override
    public String geProtocol() {
        return "TCP";
    }
}
